/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.clebersantos;

import br.com.clebersantos.util.Conecta;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 *
 * @author Cleber Santos - santos.cleber@gmail.com 11 9.8140.5393
 */
public class Main extends javax.swing.JFrame {

    private static Main instance;
    private Conecta conecta;
    private String porta;
    private Integer tempo;
    private boolean running = false;
    private Thread t;
    private String texto;
    private String dados;

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        getIni();
        conecta = new Conecta(this.porta);
        this.instance = this;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        loop = new javax.swing.JCheckBox();
        pararLooping = new javax.swing.JButton();
        mensagemEnviada = new javax.swing.JTextField();
        clickOK = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        pane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        mensagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Simulador Serial - v1.0");
        setBackground(new java.awt.Color(0, 153, 153));
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(0, 153, 153));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Digite os dados que deseja enviar!");

        loop.setBackground(new java.awt.Color(0, 153, 153));
        loop.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        loop.setForeground(new java.awt.Color(255, 255, 51));
        loop.setText("Loop");

        pararLooping.setText("Parar Looping");
        pararLooping.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pararLoopingActionPerformed(evt);
            }
        });

        mensagemEnviada.setToolTipText("Digite dua mensagem aqui");

        clickOK.setText("Enviar");
        clickOK.setName("clickOK"); // NOI18N
        clickOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clickOKActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(120, 120, 120)
                        .addComponent(loop)
                        .addGap(18, 18, 18)
                        .addComponent(pararLooping))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(mensagemEnviada, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(clickOK)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loop)
                    .addComponent(pararLooping))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(clickOK)
                    .addComponent(mensagemEnviada, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jPanel2.setBackground(new java.awt.Color(0, 153, 153));

        textArea.setColumns(20);
        textArea.setRows(5);
        pane.setViewportView(textArea);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(pane, javax.swing.GroupLayout.PREFERRED_SIZE, 501, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(pane, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jPanel3.setBackground(new java.awt.Color(0, 153, 153));

        jButton1.setBackground(new java.awt.Color(255, 51, 51));
        jButton1.setForeground(new java.awt.Color(255, 255, 0));
        jButton1.setText("Fechar Aplicação");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        mensagem.setForeground(new java.awt.Color(255, 255, 51));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mensagem)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(mensagem))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void clickOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clickOKActionPerformed
        dados = mensagemEnviada.getText();

        if (!mensagemEnviada.getText().equalsIgnoreCase("")) {

            if (loop.isSelected()) {
                if (!running) {
                    dados = mensagemEnviada.getText();
                    mensagem.setText("Enviando dados em loop");
                    running = true;
                    t = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            while (running) {
                                try {
                                    conecta.comunicacaoSerial(dados);
                                    Thread.sleep(tempo);
                                } catch (Exception e) {
                                    mensagem.setText("Erro: " + e.getMessage());
                                    System.out.println(e);
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    t.start();
                } else {
                    mensagem.setText("Você está com loop ativo, desative para reusar a aplicação");
                }
            } else {
                try {
                    System.out.println(mensagemEnviada.getText().getBytes());
                    conecta.comunicacaoSerial(dados);
                    mensagem.setText("Dados enviado com sucesso");
                } catch (Exception e) {
                    System.out.println("Erro: " + e);
                    e.printStackTrace();
                } finally {
                    mensagemEnviada.setText("");

                }
            }

        } else {
            mensagem.setText("O campo não pode ser vazio");
        }
    }//GEN-LAST:event_clickOKActionPerformed

    private void pararLoopingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pararLoopingActionPerformed
        this.loop.setSelected(false);
        this.running = false;
        t.interrupt();
        this.mensagemEnviada.setText("");
    }//GEN-LAST:event_pararLoopingActionPerformed

    public void setParametros(String porta) {
        this.porta = porta;
    }

    public void limparMensagem() {
        mensagem.setText("");
    }

    public void getIni() {
        try {

            FileReader reader = new FileReader("configPort.ini");
            BufferedReader buffer = new BufferedReader(reader);

            String linha = buffer.readLine();

            while (linha != null) {
                if (linha.contains("PORT")) {
                    this.porta = linha.substring(5, linha.length());
                } else if (linha.contains("TIME")) {
                    this.tempo = Integer.parseInt(linha.substring(5, linha.length()));
                }
                linha = buffer.readLine();
            }
            System.out.println("Porta configurada: " + this.porta);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public void escreverArea(String s) {
        System.out.println("Mensagem recebida: " + s);
        textArea.append(s + "\n");
        int maxValue = pane.getVerticalScrollBar().getMaximum();
        pane.getViewport().setViewPosition(new Point(0, maxValue));
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    public static Main getInstance() {
        return instance;
    }

    public static void setInstance(Main instance) {
        Main.instance = instance;
    }

    public Conecta getConecta() {
        return conecta;
    }

    public void setConecta(Conecta conecta) {
        this.conecta = conecta;
    }

    public String getPorta() {
        return porta;
    }

    public void setPorta(String porta) {
        this.porta = porta;
    }

    public Integer getTempo() {
        return tempo;
    }

    public void setTempo(Integer tempo) {
        this.tempo = tempo;
    }

    public String getTexto() {
        return texto;
    }

    public void setTexto(String texto) {
        this.texto = texto;
    }

    public String getDados() {
        return dados;
    }

    public void setDados(String dados) {
        this.dados = dados;
    }

    public JCheckBox getLoop() {
        return loop;
    }

    public void setLoop(JCheckBox loop) {
        this.loop = loop;
    }

    public JLabel getMensagem() {
        return mensagem;
    }

    public void setMensagem(JLabel mensagem) {
        this.mensagem = mensagem;
    }

    public JTextField getMensagemEnviada() {
        return mensagemEnviada;
    }

    public void setMensagemEnviada(JTextField mensagemEnviada) {
        this.mensagemEnviada = mensagemEnviada;
    }

    public JButton getPararLooping() {
        return pararLooping;
    }

    public void setPararLooping(JButton pararLooping) {
        this.pararLooping = pararLooping;
    }

    public JTextArea getTextArea() {
        return textArea;
    }

    public void setTextArea(JTextArea textArea) {
        this.textArea = textArea;
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clickOK;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JCheckBox loop;
    private javax.swing.JLabel mensagem;
    private javax.swing.JTextField mensagemEnviada;
    private javax.swing.JScrollPane pane;
    private javax.swing.JButton pararLooping;
    private javax.swing.JTextArea textArea;
    // End of variables declaration//GEN-END:variables
}
